package com.Xht.www.servlet;

//后端响应管理员获取用户信息的请求

import com.Xht.www.dao.UserInfoDAO;
import com.Xht.www.po.UserInfoPO;
import com.google.gson.Gson;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/UserInfoServlet")
public class UserInfoServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private UserInfoDAO userInfoDAO = new UserInfoDAO();
    private Gson gson = new Gson();

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");

        try {
            // 获取所有用户信息
            List<UserInfoPO> users = userInfoDAO.getAllUsers();

            // 不返回密码字段
            for (UserInfoPO user : users) {
                user.setPassword(null); // 确保密码不被返回
            }

            // 将用户列表转换为JSON并返回
            String jsonResponse = gson.toJson(users);
            response.getWriter().write(jsonResponse);
        } catch (Exception e) {
            e.printStackTrace();
            // 返回错误信息
            Map<String, Object> errorResult = new HashMap<>();
            errorResult.put("success", false);
            errorResult.put("message", "获取用户信息失败");
            response.getWriter().write(gson.toJson(errorResult));
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
